//
//  OffsetImageCell.m
//  ParallaxScrollingTest
//
//  Created by LiHongyao on 16/5/6.
//  Copyright © 2016年 李鸿耀. All rights reserved.
//

#import "HQYOffsetImageCell.h"

// 屏幕高度
#define  kScreenHeight  [UIScreen mainScreen].bounds.size.height
// 屏幕宽度
#define  kScreenWidth   [UIScreen mainScreen].bounds.size.width
// cell高度
#define kCellHeight 200

@implementation HQYOffsetImageCell

#pragma mark - Initialize
- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
    if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
        
        // 1、配置cell属性
        self.selectionStyle = UITableViewCellSelectionStyleNone;
        self.clipsToBounds = YES;
        
        // 2、视图加载
        [self.contentView addSubview:self.pictureView];
        [self.contentView addSubview:self.titleLabel];
        
        // 3、自定义分割线
        UIView *line = [[UIView alloc] initWithFrame:CGRectMake(0, kCellHeight - 1, kScreenWidth, 1)];
        line.backgroundColor = [UIColor lightGrayColor];
        [self.contentView addSubview:line];
    }
    return self;
}

#pragma mark - Handle offset
- (void)cancelAnimation {
    
    [self.pictureView.layer removeAllAnimations];
    
}

- (void)cellOffset {
    // 1、获取cell在屏幕中的rect
    CGRect  centerToWindow = [self convertRect:self.bounds toView:self.window];
    // 2、获取cell中心点y轴坐标
    CGFloat centerY        = CGRectGetMidY(centerToWindow);
    // 3、获取cell父视图的中心点
    CGPoint windowCenter   = self.superview.center;
    // 4、获取距离差
    CGFloat cellOffsetY = centerY - windowCenter.y;
    // 5、距离差 / 2倍父视图高度
    CGFloat offsetDig =  cellOffsetY / self.superview.frame.size.height * 2;
    // 6、计算偏移 kScreenHeight * 0.5 为图片视图的高度
    CGFloat offset    =  -offsetDig * (kScreenHeight * 0.5 - kCellHeight) / 2;
    
    CGAffineTransform transY   = CGAffineTransformMakeTranslation(0, offset);
    self.pictureView.transform = transY;
}

#pragma mark - Getters
- (UIImageView *)pictureView {
    if (!_pictureView) {
        // origin.x = - (图片高度 - 单元格高度) / 2
        _pictureView = [[UIImageView alloc]initWithFrame:CGRectMake(0, - (kScreenHeight * 0.5 - kCellHeight) / 2, kScreenWidth, kScreenHeight * 0.5)];
    }
    return _pictureView;
}


- (UILabel_Font *)titleLabel {
    if (!_titleLabel) {
        _titleLabel = [[UILabel_Font alloc] init];
        _titleLabel.bounds = CGRectMake(0, 0, kScreenWidth, 45);
        _titleLabel.center = CGPointMake(kScreenWidth * 0.5, kCellHeight * 0.5);
        _titleLabel.font = [UIFont boldSystemFontOfSize:Font(25)];
        _titleLabel.textColor = [UIColor whiteColor];
        _titleLabel.textAlignment = NSTextAlignmentCenter;
    }
    return _titleLabel;
}

@end



